package org.lee.img;

import javax.swing.*;
import java.awt.*;
import java.net.URL;

/**
 * ImageIconButtonDemo
 * 图标按钮
 *
 * @author dralee
 * @date 2021-12-29 16:41:19
 **/
public class ImageIconButtonDemo extends JFrame {
    public ImageIconButtonDemo() throws HeadlessException {
        initUI();
    }

    private URL resource(String name) {
        return getClass().getClassLoader().getResource("images/".concat(name).concat(".jpg"));
    }

    private void initUI() {
        ImageIcon iconQuit = new ImageIcon(resource("quit"));
        ImageIcon iconSave = new ImageIcon(resource("save"));
        ImageIcon iconHome = new ImageIcon(resource("home"));

        JButton btnQuit = new JButton(iconQuit);
        JButton btnSave = new JButton(iconSave);
        JButton btnHome = new JButton(iconHome);

        createLayout(btnQuit, btnSave, btnHome);

        btnQuit.addActionListener(e -> {
            int ok = JOptionPane.showConfirmDialog(null, "确定现在退出么", "温馨提示", JOptionPane.OK_CANCEL_OPTION, JOptionPane.INFORMATION_MESSAGE);
            if (ok == JOptionPane.OK_OPTION) {
                System.exit(0); // 退出
            }
        });
        btnSave.addActionListener(e -> JOptionPane.showMessageDialog(null, "保存成功^_^"));
        btnHome.addActionListener(e -> JOptionPane.showMessageDialog(null, "欢迎回家^_^"));

        // 设置窗口图标
        setIconImage(new ImageIcon(resource("android-32")).getImage());

        setTitle("JButtons");
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

    private void createLayout(JComponent... arg) {
        Container pane = getContentPane();
        GroupLayout gl = new GroupLayout(pane);
        pane.setLayout(gl);

        gl.setAutoCreateContainerGaps(true);
        gl.setAutoCreateGaps(true);
        gl.setHorizontalGroup(gl.createSequentialGroup().addComponent(arg[0]).addComponent(arg[1]).addComponent(arg[2]));
        gl.setVerticalGroup(gl.createParallelGroup().addComponent(arg[0]).addComponent(arg[1]).addComponent(arg[2]));
        gl.linkSize(arg[0], arg[1], arg[2]);

        pack();
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(() -> new ImageIconButtonDemo().setVisible(true));
    }
}
